﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using SStuff.MetaEffects.Compiler;
using SStuff.MetaEffects.Model;
using CSharp4ExpressionMetaCompiler;

namespace Sample
{
    public class InvertColorEffect : ShaderEffect
    {
        private class ShaderVariables
        {
            [Register(0)]
            public sampler2D Input { get; set; }

            [Texcoord]
            public float2 TexCoord { get; set; }

            public float4 Color { get; set; }
        }

        private static readonly PixelShader _shader;
        static InvertColorEffect()
        {
            Expression<Action<ShaderVariables>> shaderSource = o =>
                Block.Declare(new ShaderVariables(), vars =>
                    Block.Default
                    .Assign(vars.Color, vars.Input.tex2D(vars.TexCoord))
                    .Assign(vars.Color, new float4(new float3(1,1,1) - vars.Color.xyz, vars.Color.w))
                    ._(()=>vars.Color.Return())
                );
            var hlsl = ExpressionToHlsl.TranslateToHLSL(shaderSource);
            _shader = HlslCompiler.Compile(hlsl, ShaderProfile.ps_2_0);

        }

        public InvertColorEffect()
        {
            PixelShader = _shader;
            UpdateShaderValue(InputProperty);
        }

        public Brush Input
        {
            get { return (Brush)GetValue(InputProperty); }
            set { SetValue(InputProperty, value); }
        }

        public static readonly DependencyProperty InputProperty =
            ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(InvertColorEffect), 0);

    }
}
